<template>
  <div>
    <HeadContainer class="mine-notify-letter" :title="$t('title.notifyLetter')" @back="back">
      <div v-if="load">
        <div class="load-wrap" v-for="index in 3" :key="index"></div>
      </div>
      <div v-else class="gap-col-16">
        <div class="text-subtitle font-size-12 font-weight-400 line-height-120">
          {{ $t('info.stillSendImportantLetter') }}
        </div>
        <div class="d-flex justify-space-between font-size-14 mb-1">
          <div class="font-weight-500 line-height-140">{{ $t('info.emailCreatorNew') }}</div>
          <InputSwitch v-model="emailCreatorNewValue" @click="toggleEmailCreatorNew" />
        </div>
        <div class="text-subtitle font-size-12 font-weight-400 line-height-120">
          {{ $t('info.emailCreatorNewInfo') }}
        </div>
        <div class="d-flex justify-space-between font-size-14 mb-1">
          <div class="font-weight-500 line-height-140">{{ $t('info.emailUnread') }}</div>
          <InputSwitch v-model="emailUnreadValue" @click="toggleEmailUnread" />
        </div>
        <div class="text-subtitle font-size-12 font-weight-400 line-height-120">{{ $t('info.emailUnreadInfo') }}</div>
      </div>
    </HeadContainer>
  </div>
</template>
<script setup>
import { onMounted, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { storeToRefs } from 'pinia'
import { useAccountStore } from '@/store/account'
import { useAuthDialogStore } from '@/store/auth-dialog'
import InputSwitch from '@/components/form/InputSwitch.vue'
import HeadContainer from '@/components/layout/HeadContainer.vue'
import { NOTIFY_LETTER_SWITCH } from '@/constant'
import API from '@/http'

const route = useRoute()
const router = useRouter()
const emits = defineEmits(['toPage'])

const { isLogin } = storeToRefs(useAccountStore())
const { open } = useAuthDialogStore()

function back() {
  const previousRoute = route.query.from || null
  if (previousRoute && !previousRoute.includes('mine')) {
    router.replace(previousRoute)
  } else {
    emits('toPage', 2, 'settings')
    router.replace({ name: 'mine', params: { to: 'settings' } })
  }
}

const notifyLetterList = ref(null)
async function fetchList() {
  try {
    const res = await API.Auth.notifyLetterList()
    notifyLetterList.value = res
    console.log('信息通知設定:', res)
  } catch (e) {
    console.log(e)
  }
}
fetchList()

const emailCreatorNewValue = ref(false)
const emailUnreadValue = ref(false)
const load = ref(true)

watch(
  notifyLetterList,
  (newVal) => {
    if (newVal) {
      load.value = false
      emailCreatorNewValue.value = newVal?.email_creator_new === NOTIFY_LETTER_SWITCH.TURN_ON
      emailUnreadValue.value = newVal?.email_unread === NOTIFY_LETTER_SWITCH.TURN_ON
    } else {
      fetchList()
    }
  },
  { immediate: true },
)

const toggleEmailCreatorNew = async () => {
  try {
    await API.Auth.notifyLetterSet({
      data: {
        email_creator_new: emailCreatorNewValue.value ? NOTIFY_LETTER_SWITCH.TURN_OFF : NOTIFY_LETTER_SWITCH.TURN_ON,
      },
    })
    await fetchList()
  } catch (e) {
    console.error(e)
  }
}

const toggleEmailUnread = async () => {
  try {
    await API.Auth.notifyLetterSet({
      data: { email_unread: emailUnreadValue.value ? NOTIFY_LETTER_SWITCH.TURN_OFF : NOTIFY_LETTER_SWITCH.TURN_ON },
    })
    await fetchList()
  } catch (e) {
    console.error(e)
  }
}

// 監聽登入狀態，若為 false，則檢查是否成功登入
const originalRoute = ref(null)
onMounted(() => {
  if (!isLogin.value) {
    originalRoute.value = router.currentRoute.value.fullPath
    open()
  }
})
watch(isLogin, (login) => {
  if (login && originalRoute.value) {
    router.replace(originalRoute.value)
    originalRoute.value = null
    fetchList()
  }
})
</script>
<style lang="scss" scoped>
@import '@/assets/styles/loading-skeleton.scss';

.load {
  width: 100%;

  &-wrap {
    height: 2.875rem;
    border-radius: 0.625rem;
    margin-bottom: 0.5rem;

    @include loading-skeleton;
  }
}
</style>
